/*
 * Define the global namespace and setup the listeners for the main page.
 */
var rogueAdmissions = {};
rogueAdmissions.layers = new Layers('All Layers');
rogueAdmissions.zipLayer = new Layers('zip');
rogueAdmissions.schoolLayer = new Layers('schools');
rogueAdmissions.studentLayer = new Layers('students');
rogueAdmissions.infoWindow = null;
rogueAdmissions.count = 0;
/*
 * initialize creates our map object and gets the ball rolling.
 */
rogueAdmissions.initialize = function() {
    // Instatiate a new geocoder service
    rogueAdmissions.geocoder = new google.maps.Geocoder();

    // The center point of the map is Lincoln, NB.
    var usa = new google.maps.LatLng(40.8358, -96.6452);

    rogueAdmissions.database = new Database();

    // Create a Google Map object centered at usa
    rogueAdmissions.map = new google.maps.Map(document.getElementById("contig_us_map_canvas"),
    {
        zoom : 4,
        center : usa,
        mapTypeId : google.maps.MapTypeId.ROADMAP
    });
    rogueAdmissions.update();

    /*
     * Add out even listeners from the main page
     */
    $('#updateButton').on('click', rogueAdmissions.update);
    $('#resetButton').on('click', rogueAdmissions.reset);
    $('input').keydown(function(e){
        if(e.keyCode == 13) // enter key
            rogueAdmissions.update();
    });
    $('input[name=displayby]:radio').change(function(){
        switch($('input[name=displayby]:radio:checked').val()){
        case 'school':
            $('#filter_panel').hide();
            break;
        case 'student':
            $('#filter_panel').show();
            break;
        }
    });
    //switch($('input[name=displayby]:radio:checked').val()){
}

/*
 * resets all the input fields to defualt
 */
rogueAdmissions.reset = function(){
    $('#city').val('');
    $('#state').val('WA');
    $('#zipcode').val('');
    $('#gpa_min').val(0.0);
    $('#gpa_max').val(4.0);
    $('#satM_min').val(0);
    $('#satM_max').val(800);
    $('#satV_min').val(0);
    $('#satV_max').val(800);
}

/*
 * update changes what layers are displayed on the map
 */
rogueAdmissions.update = function(){
    var state = $('#state').val().toUpperCase();
    // values for SQL
    var select;
    var from;
    var where;
    var desc;
    // Hide all the current layers
    rogueAdmissions.layers.hideAll();

    // if we need the zipcode layer...
    if($('input[name=zipRadio]:radio:checked').val() == 'true') {
        rogueAdmissions.addLayer('zip', '', rogueAdmissions.database.zipEid[state], '');
    }


    // Depending on what is selected set the values
    switch($('input[name=displayby]:radio:checked').val()){
    case 'school':
        desc = 'school';
        // Add all the school layers
        select = "'High School', 'Address'";
        from = rogueAdmissions.database.schoolEid[state];
        where = rogueAdmissions.getLocationFilter($('#city').val(), $('#state').val(), $('#zipcode').val());
        break;
    case 'student':
        desc = 'student';
        // remove/hide the highschoolLayer
        // Add all the student layers ... and filter..?
        select = "'UPortland_UniqueID' AS ID, 'HS_GPA' AS GPA, 'SAT_Verbal' AS Verbal, 'SAT_MAth' AS Math,";
        select += " 'Application_Status' AS Status, 'App_Decision_Code' AS Code,";
        select += " Confirmed, Enrolled, Gender, Legacy, UPVisits";
        from = rogueAdmissions.database.studentEid['orig'];
        stuFilter = rogueAdmissions.getStudentFilter($('#gpa_min').val(), $('#gpa_max').val(),
                                          $('#satM_min').val(), $('#satM_max').val(),
                                          $('#satV_min').val(), $('#satV_max').val(),
                                          $('#city').val(), state, $('#zipcode').val());
        locationFilter = rogueAdmissions.getLocationFilter($('#city').val(), state, $('#zipcode').val());
        console.log(locationFilter);
        where = stuFilter + ((locationFilter != '') ? (' AND ' + locationFilter) : '');
        break;
    }

    // Add a listener to the layer.  When the user clicks on the
    // particular zip code area in the layer, some information
    // about the particular zip code is displayed in the info portion
    // of the page.
    if(rogueAdmissions.layers.zip != undefined) {
        google.maps.event.addListener(rogueAdmissions.layers.zip, 'click', function(displayedArea) {
                
               
                // Get the necessary information from the clicked area
                var information = displayedArea.row['ZipCodeArea'].value + "<br>";
  
                // Format and display it in the information window for the displayed area.
                console.log("Before" + displayedArea.infoWindowHtml);
               
               displayedArea.infoWindowHtml ="";
               displayedArea.infoWindowHtml = "<div class='googft-info-window' style='font-family:sans-serif'><p><strong>Zip Code:</strong> " + information + "</p></div>";
                    
                    //create an info window and put it at the appropriate xy-coords since
                    // default info window will not work
                    var coordinate = displayedArea.latLng;
                    console.log("coordinate: " + coordinate);
                                      if(rogueAdmissions.infoWindow)
                                      {
                                      rogueAdmissions.infoWindow.close();
                                      }
                    rogueAdmissions.infoWindow = new google.maps.InfoWindow();
                    
                    //set the default info window
                    rogueAdmissions.infoWindow.setContent("<p><strong>Zip Code:</strong> " + information + "</p>");
                    rogueAdmissions.infoWindow.setPosition(coordinate);
                                      //close old info window
                    //This Displays the geocoding information so we do not want the next line of code                  
                    //rogueAdmissions.infoWindow.open(rogueAdmissions.map);
                
                                      displayedArea.latLng = null;
                console.log("After" + displayedArea.infoWindowHtml);
                });

    }
    
    
    // Create our data layers above the zip layer
    rogueAdmissions.addLayer(desc, select, from, where);
    rogueAdmissions.drawTable(select, from, where);

    // Center our view
    var address = $('#city').val() + " " + state + " " + $('#zipcode').val();
    if(address.trim() == '')
        address = "Oregon";
    centerAt(rogueAdmissions.map, address, rogueAdmissions.geocoder);
    if($('#zipcode').val() != '')
        rogueAdmissions.map.setZoom(11);
    else if($('#city').val() != '')
        rogueAdmissions.map.setZoom(9);
    else // state
        rogueAdmissions.map.setZoom(6);

	if(rogueAdmissions.layers.student != undefined)
	{
		google.maps.event.addListener(rogueAdmissions.layers.student, 'click', function(displayedArea) {
		

		// Get the necessary information from the clicked area
		var info = [];
		info[0] = displayedArea.row['HS_GPA'].value;
		info[1] = displayedArea.row['App_Decision_Code'].value;
		info[2] = displayedArea.row['First_Contact_Code'].value;
		info[3] = displayedArea.row['SAT_Verbal'].value;
		info[4] = displayedArea.row['SAT_MAth'].value;
		info[5] = displayedArea.row['Planned_Major_Code'].value;
		
		//format and display in info window
		console.log("Before" + displayedArea.infoWindowHtml);
		/*
		displayedArea.infoWindowHtml = "<div class='googft-info-window' style='font-family:sans-serif'>"
		+ "<p><strong>GPA:</strong> " + info[0] + "</p>"
		+ "<p><strong>App Status Code:</strong> " + info[1] + "</p>"
		+ "<p><strong>Contact Code:</strong> " + info[2] + "</p>"
		+ "<p><strong>SAT Verbal:</strong> " + info[3] + "</p>"
		+ "<p><strong>SAT Math:</strong> " + info[4] + "</p>"
		+ "<p><strong>Planned Major:</strong> " + info[5] + "</p></div>";
		*/
        //create an info window and put it at the appropriate xy-coords since
        // default info window will not work
        var coordinate = displayedArea.latLng;
        console.log("coordinate: " + coordinate);
		
		if(rogueAdmissions.infoWindow)
        {
        	rogueAdmissions.infoWindow.close();
        }
		
        rogueAdmissions.infoWindow = new google.maps.InfoWindow();		

		//set the default info window
        rogueAdmissions.infoWindow.setContent("<div class='googft-info-window' style='font-family:sans-serif'>"
		+"<p><strong>GPA:</strong> " + info[0] + "</p>"
		+ "<p><strong>App Status Code:</strong> " + info[1] + "</p>"
		+ "<p><strong>Contact Code:</strong> " + info[2] + "</p>"
		+ "<p><strong>SAT Verbal:</strong> " + info[3] + "</p>"
		+ "<p><strong>SAT Math:</strong> " + info[4] + "</p>"
		+ "<p><strong>Planned Major:</strong> " + info[5] + "</p>"
		+ "</div>");
        rogueAdmissions.infoWindow.setPosition(coordinate);
        //rogueAdmissions.infoWindow.open(rogueAdmissions.map);



		});
	}
}

/*
 * addLayers - creates multiple layers given a dictionary to key eid pairs
 */
rogueAdmissions.addLayer = function(desc, select, from, where){
    switch (desc){
    case 'zip':
        rogueAdmissions.layers.zip = rogueAdmissions.createFusionLayer(select, from, where);
        break;
    case 'student':
        rogueAdmissions.layers.student = rogueAdmissions.createFusionLayer(select, from, where);
        break;
    case 'school':
        rogueAdmissions.layers.school = rogueAdmissions.createFusionLayer(select, from, where);
        break;
    }
}

/*
 * createFusionLayer - adds a layer to the map and returns the layer object
 * select is the columns to get
 * from is the table - an EID value
 * where is our sql style where clause
 */
rogueAdmissions.createFusionLayer = function(select, from, where){
    var layer = new google.maps.FusionTablesLayer({
            query: {
                from: from,
                where: where
            },
    });
    layer.setMap(rogueAdmissions.map);
    return layer;
}

/*
 * getLocationFilter - builds a where string to get the appropriate data from the tables
 *  based on the required city, state, and zip
 */
rogueAdmissions.getLocationFilter = function(city, state, zip){
    var whereStr = '';
    if(city != '')
        whereStr += "Address CONTAINS IGNORING CASE '" + city + "'";
    if(state != ''){
        if(whereStr != '') whereStr += " AND ";
        whereStr += "Address CONTAINS '" + state + "'";
    }
    if(zip != ''){
        if(whereStr != '') whereStr += " AND ";
        whereStr += "Address CONTAINS '" + zip + "'";
    }
    return whereStr;
}

/*
 * getStudentFilter - A student data specific filter builder which builds a query where string
 *  based off of the student's academic data.
 */
rogueAdmissions.getStudentFilter = function(minGpa, maxGpa, minMathSat, maxMathSat, minVerbalSat, maxVerbalSat){
    MAXSAT = 800;
    MAXGPA = 4;
    // we need to handle bad input
    if(minGpa > maxGpa) {minGpa = 0; maxGpa = MAXGPA;}
    if(minGpa < 0 || minGpa > MAXGPA) minGpa = 0;
    if(maxGpa < 0 || maxGpa > MAXGPA) maxGpa = MAXGPA;
    if(minMathSat > maxMathSat) {minMathSat = 0; maxMathSat=MAXSAT;}
    if(minMathSat < 0 || minMathSat > MAXSAT) minMathSat = 0;
    if(maxMathSat < 0 || maxMathSat > MAXSAT) maxMathSat = MAXSAT;
    if(minVerbalSat > maxVerbalSat) {minVerbalSat = 0; maxVerbalSat=MAXSAT;}
    if(minVerbalSat < 0 || minVerbalSat > MAXSAT) minVerbalSat = 0;
    if(maxVerbalSat < 0 || maxVerbalSat > MAXSAT) maxVerbalSat = MAXSAT;

    var whereStr;
    whereStr = "HS_GPA >= " + minGpa + " AND HS_GPA <= " + maxGpa;
    whereStr += " AND SAT_MAth >= " + minMathSat + " AND SAT_MAth <= " + maxMathSat;
    whereStr += " AND SAT_Verbal >= " + minVerbalSat + " AND SAT_Verbal <= " + maxVerbalSat;
    return whereStr;
}

/*
 * drawTable()
 * Takes the appropriate arguments to query google fusion tables
 * @param select is either 'student' or 'school' this influences which columns we retrieve
 * @param from is an eid of a table
 * @param where is the where string
 */
rogueAdmissions.drawTable = function (select, from, where){
    var query = "SELECT " + select +
            ' FROM ' + from +
            ' WHERE ' + where;
    var queryText = encodeURIComponent(query);
    var gvizQuery = new google.visualization.Query(
        'http://www.google.com/fusiontables/gvizdata?tq=' + queryText);

    gvizQuery.send(function(response) {
        var table = new google.visualization.Table(
            document.getElementById('tabs-2'));
            table.draw(response.getDataTable(), {
            showRowNumber: true
        });
    });
}
